package com.eva.notice.biz;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.eva.dao.system.model.SystemNotice;
import com.eva.framework.config.AppConfig;
import com.eva.notice.biz.vo.SystemNoticeProfileVO;
import com.eva.service.system.SystemNoticeService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component
public class SystemNoticeBiz {

    @Resource
    private SystemNoticeService systemNoticeService;

    @Resource
    private AppConfig appConfig;

    /**
     * 查询最新的通知列表
     *
     * @param count 查询数量
     * @return List<SystemNoticeProfileVO>
     */
    public List<SystemNoticeProfileVO> findLatestList(Integer count) {
        return this.findLatestList(count, appConfig.getId());
    }

    /**
     * 查询最新的通知列表
     *
     * @param count 查询数量
     * @param scope 作用域
     * @return List<SystemNoticeProfileVO>
     */
    public List<SystemNoticeProfileVO> findLatestList(Integer count, String scope) {
        // 查询通知列表
        QueryWrapper<SystemNotice> queryWrapper = new QueryWrapper<>();
        Date now = new Date();
        queryWrapper.lambda()
                // v5.1.0，scope字段更改为scopes
                .like(SystemNotice::getScopes, "," + scope + ",")
                // v5.1.0，调整开始时间的验证条件
                .and(q ->
                        q.le(SystemNotice::getStartTime, now)
                                .or()
                                .isNull(SystemNotice::getStartTime))
                // v5.1.0，调整结束时间的验证条件
                .and(q ->
                        q.ge(SystemNotice::getEndTime, now)
                                .or()
                                .isNull(SystemNotice::getEndTime))
                .eq(SystemNotice::getDisabled, Boolean.FALSE)
                .eq(SystemNotice::getDeleted, Boolean.FALSE)
                .orderByDesc(SystemNotice::getCreatedAt)
                .last("limit " + count);
        List<SystemNotice> notices = systemNoticeService.findList(queryWrapper);
        // 转为List<SystemNoticeProfileVO>
        List<SystemNoticeProfileVO> profiles = new ArrayList<>();
        for (SystemNotice notice : notices) {
            SystemNoticeProfileVO profile = new SystemNoticeProfileVO();
            BeanUtils.copyProperties(notice, profile);
            profiles.add(profile);
        }
        return profiles;
    }
}
